import { BaseComponent } from '../base/BaseComponent';
const { ccclass, property } = cc._decorator;

/**加载项 */
export class LoadingItem {
  /**
   * @param name 加载项名称
   * @param prgWeight 加载项占比权重值
   * @param total 总加载数
   * @param finished 已完成数
   */
  constructor(
    public name = "",
    public prgWeight = 100,
    public total = 1,
    public finished = 0,
  ) { }
}

/**加载页参数 */
export class LoadingPageProp {
  constructor(
    public loadingFinishCbk: Function
  ) { }
}

/**加载页 */
@ccclass
export class LoadingPage extends BaseComponent<LoadingPageProp> {

  @property(cc.ProgressBar)
  prgBar: cc.ProgressBar = null

  @property(cc.Label)
  lbProgress: cc.Label = null

  @property(cc.Label)
  lbDesc: cc.Label = null

  loadingItems: LoadingItem[] = []

  totalWeight = 0

  /**添加加载项 */
  addItem(item: LoadingItem) {
    this.loadingItems.push(item)
    this.totalWeight = this.loadingItems.reduce((p, c) => p + c.prgWeight, 0)
    return item
  }

  /**已完成的比重 */
  getFinishedWeight() {
    return this.loadingItems.reduce((p, c) => p + (c.finished / c.total) * c.prgWeight, 0)
  }

  /**更新单个加载项进度 */
  updateItem(item: LoadingItem, finished: number, total?: number) {
    item.finished = finished
    if (total) {
      item.total = total
    }
    console.log(`${item.name}已加载:${finished + '/' + item.total}`)
    this.lbDesc.string = `${item.name}已加载:${finished + '/' + item.total}`;
    this.refreshPrg()
  }

  /**计算并刷新进度 */
  refreshPrg() {
    const finishedWeight = this.getFinishedWeight()
    this.setPrg(finishedWeight / this.totalWeight)
  }

  /**设置进度值 */
  setPrg(value: number) {
    if (this.prgBar.progress != value) {
      // console.log(`prgValue:`, value);
      this.prgBar.progress = value
      this.lbProgress.string = `${Math.ceil(value * 100)}%`;
      if (value >= 1) {
        if (this.prop?.loadingFinishCbk) {
          this.prop.loadingFinishCbk()
          this.prop = null
        }
      }
    }
  }

}